<?php
namespace Asiah\SiklusBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
use Asiah\SiklusBundle\Form\Type\UserType;
use Asiah\SiklusBundle\Entity\User;

class UserController extends Controller
{
	public function loginAction(){
		$request = $this -> getRequest();
		$session = $request -> getSession();

		// get the login error if there is one aaaaa
		if($request -> attributes -> has(SecurityContext::AUTHENTICATION_ERROR)) {
			$error = $request -> attributes -> get(SecurityContext::AUTHENTICATION_ERROR);
		} else {
			$error = $session -> get(SecurityContext::AUTHENTICATION_ERROR);
		}

		$username = null;
		if($this->get('security.context')->isGranted('ROLE_USER')) {
			$usernow = $this->container->get('security.context')->getToken()->getUser();
			$username = $usernow->getUsername();
		}
		$parameter = array ('last_username' => $session -> get(SecurityContext::LAST_USERNAME), 'error' => $error, );
		return $this -> render('AsiahSiklusBundle:User:login.html.twig', $parameter);
	}
	public function registerAction(Request $request){
		if ($this->get('security.context')->isGranted('ROLE_USER')){
			return $this -> redirect($this -> generateUrl('home'));
		}
		$pengguna = new User();
		$form = $this->createForm(new UserType(), $pengguna);

		if($request -> getMethod() == 'POST') {
			$form -> bindRequest($request);
			if($form -> isValid()) {
				$em = $this -> getDoctrine() -> getEntityManager()-> getRepository('AsiahSiklusBundle:User');
				$pengguna = $form -> getData();
				$em->saveNewUser($pengguna);

				return $this -> redirect($this -> generateUrl('home'));
			}
		}
		return $this -> render('AsiahSiklusBundle:User:register.html.twig', array('form' => $form -> createView(), ));
	}
}
